from datetime import datetime
from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean, ForeignKey, Index
from sqlalchemy.orm import relationship
from backend.infrastructure.database import db


class Notification(db.Model):
    """通知记录表"""
    __tablename__ = 'notifications'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=True, comment='接收用户ID，为空表示管理员公告')
    title = Column(String(200), nullable=False, comment='通知标题')
    content = Column(Text, nullable=False, comment='通知内容')
    notification_type = Column(String(50), nullable=False, comment='通知类型：system-系统通知,intervention-干预提醒,vision-视力检查,share-社交分享,announcement-公告')
    priority = Column(String(20), default='normal', comment='优先级：low-低,normal-普通,high-高,urgent-紧急')
    status = Column(String(20), default='unread', comment='状态：unread-未读,read-已读,deleted-已删除,draft-草稿,published-已发布')
    read_at = Column(DateTime, nullable=True, comment='阅读时间')
    related_type = Column(String(50), nullable=True, comment='关联类型：vision_record,intervention_record,social_share')
    related_id = Column(Integer, nullable=True, comment='关联记录ID')
    template_id = Column(String(100), nullable=True, comment='微信模板消息ID')
    wechat_sent = Column(Boolean, default=False, comment='是否已发送微信消息')
    wechat_sent_at = Column(DateTime, nullable=True, comment='微信消息发送时间')
    target_users = Column(String(50), nullable=True, comment='目标用户类型：all-所有用户,admin-管理员,doctor-医生,parent-家长')
    sent_count = Column(Integer, default=0, comment='实际发送用户数量')
    created_by = Column(Integer, ForeignKey('users.id'), nullable=True, comment='创建者用户ID，用于管理员公告')
    published_at = Column(DateTime, nullable=True, comment='发布时间')
    sent_at = Column(DateTime, nullable=True, comment='发送时间')
    scheduled_at = Column(DateTime, nullable=True, comment='计划发送时间')
    expire_at = Column(DateTime, nullable=True, comment='过期时间')
    created_at = Column(DateTime, default=datetime.now, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联关系 - 修复冲突的关系定义
    user = relationship("User", foreign_keys=[user_id], back_populates="notifications")
    creator = relationship("User", foreign_keys=[created_by], back_populates="created_notifications")
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'title': self.title,
            'content': self.content,
            'notification_type': self.notification_type,
            'priority': self.priority,
            'status': self.status,
            'read_at': self.read_at.isoformat() if self.read_at else None,
            'related_type': self.related_type,
            'related_id': self.related_id,
            'template_id': self.template_id,
            'wechat_sent': self.wechat_sent,
            'wechat_sent_at': self.wechat_sent_at.isoformat() if self.wechat_sent_at else None,
            'target_users': self.target_users,
            'sent_count': self.sent_count,
            'created_by': self.created_by,
            'published_at': self.published_at.isoformat() if self.published_at else None,
            'sent_at': self.sent_at.isoformat() if self.sent_at else None,
            'scheduled_at': self.scheduled_at.isoformat() if self.scheduled_at else None,
            'expire_at': self.expire_at.isoformat() if self.expire_at else None,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }


class NotificationSetting(db.Model):
    """通知设置表"""
    __tablename__ = 'notification_settings'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False, comment='用户ID')
    notification_type = Column(String(50), nullable=False, comment='通知类型')
    enabled = Column(Boolean, default=True, comment='是否启用')
    wechat_enabled = Column(Boolean, default=True, comment='是否启用微信推送')
    app_enabled = Column(Boolean, default=True, comment='是否启用应用内通知')
    created_at = Column(DateTime, default=datetime.now, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联关系
    user = relationship("User", back_populates="notification_settings")
    
    # 唯一约束：每个用户每种通知类型只能有一条设置
    __table_args__ = (
        Index('idx_user_notification_type_unique', 'user_id', 'notification_type', unique=True),
    )
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'notification_type': self.notification_type,
            'enabled': self.enabled,
            'wechat_enabled': self.wechat_enabled,
            'app_enabled': self.app_enabled,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }


class WechatTemplate(db.Model):
    """微信模板消息配置表"""
    __tablename__ = 'wechat_templates'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    template_id = Column(String(100), nullable=False, unique=True, comment='微信模板ID')
    template_name = Column(String(100), nullable=False, comment='模板名称')
    notification_type = Column(String(50), nullable=False, comment='对应的通知类型')
    title = Column(String(200), nullable=False, comment='模板标题')
    content_template = Column(Text, nullable=False, comment='内容模板，支持变量替换')
    variables = Column(Text, nullable=True, comment='变量说明，JSON格式')
    status = Column(String(20), default='active', comment='状态：active-启用,inactive-停用')
    created_at = Column(DateTime, default=datetime.now, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'template_id': self.template_id,
            'template_name': self.template_name,
            'notification_type': self.notification_type,
            'title': self.title,
            'content_template': self.content_template,
            'variables': self.variables,
            'status': self.status,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }


class NotificationLog(db.Model):
    """通知发送日志表"""
    __tablename__ = 'notification_logs'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    notification_id = Column(Integer, ForeignKey('notifications.id'), nullable=False, comment='通知ID')
    send_type = Column(String(20), nullable=False, comment='发送类型：wechat-微信,app-应用内')
    status = Column(String(20), nullable=False, comment='发送状态：success-成功,failed-失败')
    error_message = Column(Text, nullable=True, comment='错误信息')
    retry_count = Column(Integer, default=0, comment='重试次数')
    sent_at = Column(DateTime, default=datetime.now, comment='发送时间')
    
    # 关联关系
    notification = relationship("Notification")
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'notification_id': self.notification_id,
            'send_type': self.send_type,
            'status': self.status,
            'error_message': self.error_message,
            'retry_count': self.retry_count,
            'sent_at': self.sent_at.isoformat() if self.sent_at else None
        } 